package top.kaoshanji.p4ch05a.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * SqlSession工具类
 * @author kaoshanji
 * ^_^
 * create time 2025/4/17 14:07
 */
public class SqlSessionUtil {

    private static SqlSessionFactory sqlSessionFactory = null;

    // 初始化 SqlSessionFactory 对象
    static {
        // MyBatis 核心配置文件名称
        String fileName = "mybatis-config.xml";
        try {
            // 获取文件输入流
            InputStream inputStream = Resources.getResourceAsStream(fileName);
            // 创建 SqlSessionFactoryBuilder
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            // 创建 SqlSessionFactory
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 SqlSession
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }

    /**
     * 关闭  SqlSession
     * @param sqlSession SqlSession
     */
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }


}
